#include "pwm_measure.h"

// 全局变量定义
PWM_MeasureTypeDef pwm_data = {0, 0, 0.0f, 0};

// 静态变量(仅在本文件中使用)
static uint32_t rising_edge = 0;    // 上升沿捕获值
static uint32_t falling_edge = 0;   // 下降沿捕获值
static uint8_t capture_state = 0;   // 捕获状态:0-等待上升沿,1-等待下降沿

// 初始化PWM测量
void PWM_Measure_Init(TIM_HandleTypeDef *htim) {
    // 启动输入捕获
    HAL_TIM_IC_Start_IT(htim, TIM_CHANNEL_1);
}

// 获取测量结果
void PWM_GetMeasurements(PWM_MeasureTypeDef *data) {
    if (data && pwm_data.data_ready) {
        // 复制数据
        data->period_us = pwm_data.period_us;
        data->pulse_width_us = pwm_data.pulse_width_us;
        data->duty_cycle = pwm_data.duty_cycle;
        
        // 清除就绪标志
        pwm_data.data_ready = 0;
    }
}

// 处理捕获事件(在中断中调用)
void PWM_ProcessCapture(TIM_HandleTypeDef *htim) {
    if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1) {
        // 根据当前状态处理不同边沿
        if (capture_state == 0) {
            // 上升沿捕获
            rising_edge = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
            
            // 切换为下降沿捕获
            __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
            
            // 更新状态
            capture_state = 1;
        } 
        else if (capture_state == 1) {
            // 下降沿捕获
            falling_edge = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
            
            // 计算脉冲宽度
            if (falling_edge > rising_edge) {
                pwm_data.pulse_width_us = falling_edge - rising_edge;
            } else {
                // 处理定时器溢出情况
                pwm_data.pulse_width_us = (0xFFFF - rising_edge) + falling_edge;
            }
            
            // 切换为上升沿捕获，准备测量周期
            __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_RISING);
            
            // 更新状态，准备下一次周期测量
            capture_state = 2;
        }
        else if (capture_state == 2) {
            // 再次捕获上升沿，计算周期
            uint32_t current_rising = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
            
            if (current_rising > falling_edge) {
                pwm_data.period_us = current_rising - falling_edge;
            } else {
                // 处理定时器溢出情况
                pwm_data.period_us = (0xFFFF - falling_edge) + current_rising;
            }
            
            // 计算占空比(避免除零错误)
            if (pwm_data.period_us > 0) {
                pwm_data.duty_cycle = (float)pwm_data.pulse_width_us / pwm_data.period_us * 100.0f;
            } else {
                pwm_data.duty_cycle = 0.0f;
            }
            
            // 设置数据就绪标志
            pwm_data.data_ready = 1;
            
            // 重置状态，准备下一次测量
            rising_edge = current_rising;
            capture_state = 1;
            
            // 保持为下降沿捕获
            __HAL_TIM_SET_CAPTUREPOLARITY(htim, TIM_CHANNEL_1, TIM_INPUTCHANNELPOLARITY_FALLING);
        }
    }
}
